package org.example.myleet.learn.bank;

import java.math.BigDecimal;
import java.util.Random;

public class BadExample {

    private static final Random rand = new Random();

    public static void main(String[] args) {
        //initialization
        Account a = new Account("A", 1000000);
        Account b = new Account("B", 0);
        printState(a, b);
        long start = System.currentTimeMillis();
        //transfer many times asynchronously
        for (int i = 0; i < 1000; ++i) {
            Thread t = new Thread(() -> {
                BigDecimal transferAmount = BigDecimal.valueOf(rand.nextInt(1000));
                a.withdraw(transferAmount);
                b.transfer(transferAmount);
            });
            t.start();
        }
        //print state again and the total amount will not equal to the initial amount
        printState(a, b);
        System.out.println("time = " + (System.currentTimeMillis() - start) + "ms");
    }

    private static synchronized void printState(Account... accounts) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Account account : accounts) {
            totalAmount = totalAmount.add(account.getBalance());
            System.out.println(account);
        }
        System.out.println("Total amount = " + totalAmount.toPlainString());
    }
}
